//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package chat_dao

import (
	"context"
	"fmt"
	"sort"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_chat_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type GroupMsgIndexDbItem struct {
	MsgIndexId  string `bson:"_id"` //自动生成
	MsgId       string `bson:"msgId"`
	ChatGroupId string `bson:"chatGroupId"`
	TimeStamp   int64  `bson:"timeStamp"`
}

type _GroupMsgIndexDao struct {
	mc *mongo.Collection
}

func newGroupMsgIndexDao(db *mongo.Database) (*_GroupMsgIndexDao, error) {
	mc := db.Collection(db_ns.DB_NS_CHAT + "group_msg_index")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"chatGroupId", 1}, {"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_GroupMsgIndexDao{mc: mc}, nil
}

func (db *_GroupMsgIndexDao) Insert(ctx context.Context, dbItem *GroupMsgIndexDbItem) error {
	dbItem.MsgIndexId = db.genMsgIndexId(dbItem.ChatGroupId, dbItem.MsgId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_GroupMsgIndexDao) genMsgIndexId(chatGroupId, msgId string) string {
	return fmt.Sprintf("%s:%s", chatGroupId, msgId)
}

func (db *_GroupMsgIndexDao) Exist(ctx context.Context, chatGroupId, msgId string) (bool, error) {
	msgIndexId := db.genMsgIndexId(chatGroupId, msgId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": msgIndexId})
	return count > 0, err
}

func (db *_GroupMsgIndexDao) Get(ctx context.Context, chatGroupId, msgId string) (*GroupMsgIndexDbItem, error) {
	msgIndexId := db.genMsgIndexId(chatGroupId, msgId)
	retItem := &GroupMsgIndexDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": msgIndexId}).Decode(retItem)
	return retItem, err
}

func (db *_GroupMsgIndexDao) List(ctx context.Context, chatGroupId string, refTimeStamp int64, listType project_chat_api.LIST_MSG_TYPE, limit uint32) ([]*GroupMsgIndexDbItem, error) {
	query := bson.M{"chatGroupId": chatGroupId}
	order := 1
	if listType == project_chat_api.LIST_MSG_TYPE_LIST_MSG_AFTER {
		query["timeStamp"] = bson.M{"$gt": refTimeStamp}
		order = 1
	} else if listType == project_chat_api.LIST_MSG_TYPE_LIST_MSG_BEFORE {
		query["timeStamp"] = bson.M{"$lt": refTimeStamp}
		order = -1
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetLimit(int64(limit)).SetSort(bson.M{"timeStamp": order}))
	if err != nil {
		return nil, err
	}
	retList := []*GroupMsgIndexDbItem{}
	err = cursor.All(ctx, &retList)
	if err != nil {
		return nil, err
	}
	sort.SliceStable(retList, func(i, j int) bool {
		return retList[i].TimeStamp < retList[j].TimeStamp
	})
	return retList, err
}
